package com.mediocre.service.impl;

import com.mediocre.entity.Book;
import com.mediocre.service.BookService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

/**
 * 监听消息队列中的内容
 * 使用@EnableRabbit+@RabbitListener监听消息队列中的内容。
 * @EnableRabbit：表示开启基于注解的rabbitmq。
 * @RabbitListener：表示监听某个队列的内容。
 *
 * 注意：多个带有@RabbitListener()注解的方法中，如果监听了相同的队列，则 多个方法自动轮询监听该队列
 */
@Service
public class BookServiceImpl implements BookService {
    /**
     * 注解：@RabbitListener(queues = "queue2")，表示监听queue2这个队列的内容
     *
     * @param book
     */
    @RabbitListener(queues = "queue2")
    @Override
    public void receive(Book book) {
        System.out.println("收到 queue2 消息:" + book);
    }

    /**
     * 接收消息的第二种方式：
     *
     * @param message
     */
    @RabbitListener(queues = {"hello", "queue2"})
    @Override
    public void receive(Message message) {
        //获取消息体
        byte[] body = message.getBody();
        System.out.println(body);   //[B@fe4bdc2
        //获得消息属性
        MessageProperties properties = message.getMessageProperties();
        System.out.println(properties);
        /*
        MessageProperties [headers={__TypeId__=com.example.bean.Book}, contentType=application/json,
        contentEncoding=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0,
        redelivered=false, receivedExchange=exchange.direct, receivedRoutingKey=aiguigu, deliveryTag=1,
        consumerTag=amq.ctag-ynkD05MwnffSCo9h7W5DGA, consumerQueue=aiguigu]
         */
    }
}
